package top.leinx.fxnotes.control;

/**
 * @Author : xiaolei
 * @DateTime: 2021/3/25 10:43 上午
 */

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class RadioButtonExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        // 创建4个RadioButton控件对象
        RadioButton rb1 = new RadioButton("First");
        RadioButton rb2 = new RadioButton("Second");
        RadioButton rb3 = new RadioButton("Third");
        RadioButton rb4 = new RadioButton("Fourth");

        // 创建一个开关分组对象
        ToggleGroup group = new ToggleGroup();

        // 把4个RadioButton控件的开关分组设置为group
        rb1.setToggleGroup(group);
        rb2.setToggleGroup(group);
        rb3.setToggleGroup(group);
        rb4.setToggleGroup(group);

        // 设置分组的选中控件
        group.selectToggle(rb1);

        // 创建一个 HBox，并把4个RadioButton组件添加到 Hbox
        HBox radioBox = new HBox(5.0, rb1, rb2, rb3, rb4);
        // 创建一个测试RadioButton选中状态的按钮
        Button button = new Button("输出选中的RadioButton");
        button.setOnAction(event -> {
            RadioButton selected = (RadioButton) group.getSelectedToggle();
            System.out.println("当前选中:" + selected.getText());

            System.out.println("分组 group 中的所有 RadioButton: ");
            for(Toggle rb: group.getToggles()) {
                System.out.println(rb);
            }
        });
        // 创建一个 VBox，排列 HBox 和 Button
        VBox box = new VBox(5.0, radioBox, button);

        primaryStage.setTitle("RadioButton 示例");
        primaryStage.setScene(new Scene(box, 300, 100));
        primaryStage.show();
    }
}
